package com.xuxiao.springbootexp03.Controller;

import com.xuxiao.springbootexp03.Entity.Region;
import com.xuxiao.springbootexp03.Service.RegionPropertiesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.List;

//@ResponseBody
@Controller
public class RegionPropertiesController {

    @Autowired
    private RegionPropertiesService service;

    private final String ALL_REGION="all";

    @RequestMapping(value = "/country/{country}")
    public String getByCountry(@PathVariable String country, Model model) {
        List<Region> regions;
        if(ALL_REGION.equals(country)) {
            regions=service.getAllRegion();
            regions.remove(0);
        }else{
            regions=service.getByCountry(country);
        }

        model.addAttribute("regions", regions);
        model.addAttribute("country",country);
        return "index";
    }

    @RequestMapping("/home")
    public String getAllRegion(Model model) {
        List<Region> regions=service.getAllRegion();
        regions.remove(0);
        model.addAttribute("regions",regions);
        model.addAttribute("country","all");
        return "index";
    }

    @ResponseBody
    @RequestMapping("/getCountryJson/{country}")
    public List<Region> getJson(@PathVariable String country) {
        if(ALL_REGION.equals(country)) {
            return service.getAllRegion();
        }
        return service.getByCountry(country);
    }

}
